<template>
  <div style="width: 500px">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="原始密码" prop="password">
        <el-input v-model.trim="form.password" show-password type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model.trim="form.newPassword" show-password type="newPassword" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPassword">
        <el-input v-model.trim="form.checkPassword" show-password type="checkPassword" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div>
      <el-button @click="reset">重 置</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </div>
</template>

<script>
  import { doChangePwd } from '@/api/system/user'
  import { isHaveBlankValid, isUsernameValid } from '@/utils/validator'

  export default {
    name: 'ChangePwd',
    data() {
      return {
        form: {
          password: '',
          newPassword: '',
          checkPassword: '',
        },
        rules: {
          password: [{ required: true, trigger: 'blur', message: '请输入原始密码' }],
          newPassword: [
            { required: true, trigger: 'blur', message: '请输入新密码' },
            { validator: isHaveBlankValid, trigger: 'blur' },
            { validator: isUsernameValid, trigger: 'blur' },
          ],
          checkPassword: [
            { validator: isUsernameValid, trigger: 'blur' },
            { validator: isHaveBlankValid, trigger: 'blur' },
            { required: true, validator: this.validatePassword },
          ],
        },
      }
    },
    created() {},
    methods: {
      validatePassword(rule, value, callback) {
        if (value === '') {
          callback(new Error('请输入确认密码'))
        } else if (value !== this.form.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      reset() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
      },
      submit() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const { success, msg } = await doChangePwd(this.form)
            if (success) {
              this.reset()
              this.$baseMessage('修改成功，请重新登录', 'success')
              await this.$store.dispatch('user/logout')
              setTimeout(() => {
                this.$router.push('/login')
              }, 3000)
            } else {
              this.$baseMessage(msg, 'error')
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
